package ecg.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;

import ecg.itf.dao.ECGDao;
import ecg.util.bean.PageDataBean;

public class PageUtil extends ActionSupport
{
	ECGDao ecgDao;
	
	private static PageUtil singleton;
	
	protected PageUtil(){}
	
	public static PageUtil getInstance()
	{
		if(singleton == null)
		{
			singleton = new PageUtil();
		}
		
		return singleton;
	}
	
	public static final int COUNT_PER_PAGE = 20;
	private static int pagePerBlock = 10;
	
	// 블럭당 페이지수를 반환하는 메서드.
	public static int getPagePerBlock()
	{
		return pagePerBlock;
	}
	
	
	public Map getPageInfoData(int totalDataCount, int pageNumber) throws Exception
	{
		
			// 총페이지 수.
			int totalPageCount = this.calculateTotalPageCount(totalDataCount);
			
			
			// 가져올 레코드셋중에서 첫번째 행.
			int firstRow = (pageNumber - 1) * COUNT_PER_PAGE + 1;
			
			// 가져올 레코드셋중에서 마지막번째 행.
			int endRow = firstRow + COUNT_PER_PAGE -1;
			
			if(endRow > totalDataCount)
			{
				endRow = totalDataCount;
			}
			
			int startRow = firstRow - 1;
			int limitRowCount = endRow - firstRow + 1;
			
			
			
			
			
			Map pageInfoDataMap = new HashMap();
			pageInfoDataMap.put("pageNumber",pageNumber);
			pageInfoDataMap.put("totalPageCount", totalPageCount);
			pageInfoDataMap.put("startRow", startRow);
			pageInfoDataMap.put("limitRowCount", limitRowCount);
			pageInfoDataMap.put("pagePerBlock", pagePerBlock);
			pageInfoDataMap.put("countPerPage", COUNT_PER_PAGE);
			
			
			// 시작 페이지와 마지막 페이지 구하기.
			int[] startEndPage = this.getStartEndPage(pageInfoDataMap);
			
			pageInfoDataMap.put("startPage",startEndPage[0]);
			pageInfoDataMap.put("endPage",startEndPage[1]);
			
			return pageInfoDataMap;
	
	}
	
	// 총데이터수를 전달받아 총페이지수를 반환한다.
	private static int calculateTotalPageCount(int totalDataCount)
	{
		if(totalDataCount == 0)
		{
			return 0;
		}
		int pageCount = totalDataCount / COUNT_PER_PAGE;
		if(totalDataCount % COUNT_PER_PAGE > 0)
		{
			pageCount ++;
		}
		return pageCount;
	}
	
	
	// 시작페이지와 끝페이지를 얻는 메서드.
	private static int[] getStartEndPage(Map pageInfoDataMap)
	{
		int[] startEndPage = new int[2];
		
		// 시작 페이지 번호와 끝페이지 번호를 설정한다.
		if((Integer)pageInfoDataMap.get("totalPageCount") > 0)
		{
			int beginPageNumber = (((Integer)pageInfoDataMap.get("pageNumber") - 1) / pagePerBlock) * pagePerBlock + 1;
			int endPageNumber = (((beginPageNumber-1) + pagePerBlock) / pagePerBlock) * pagePerBlock;
			
			//int endPageNumber = beginPageNumber + 9;
			
			if(endPageNumber > (Integer)pageInfoDataMap.get("totalPageCount"))
			{
				endPageNumber = (Integer)pageInfoDataMap.get("totalPageCount");
			}
			
			
			startEndPage[0] = beginPageNumber;
			startEndPage[1] = endPageNumber;
			
		}
		
		return startEndPage;
		
	}
}
